import { ref, reactive } from 'vue'
import app from '@/app'
import store from '@/app/store'
import { get } from '@/api/provider/miravia_reverse'
import { item } from '@/api/provider/miravia_order'
import { limit } from '@/api/store/goods'

// 初始化
const reverseStore = store()

// 选中行
reverseStore.select = ref([])
reverseStore.selectData = []

// 清空
reverseStore.selectEmpty = () => {
  reverseStore.select.value = []
  reverseStore.selectData = []
}

// 分页
reverseStore.page = reactive({
  current: 1,
  pageSize: 50,
  total: 0,
  pageSizeOptions: [50, 100],
  loading: false
})

// 查询类型
reverseStore.where = reactive({ 
  key: 'number', 
  value: '',
  time: []
})

// 生成查询数据
reverseStore.getWhere = () => {
  // 查询方式
  const where = { 
    [reverseStore.where.key]: reverseStore.where.value,
    time: reverseStore.where.time 
  }
  // 合并数据
  return Object.assign(where, reverseStore.getData())
}

reverseStore.get = () => {
  reverseStore.getData().page = reverseStore.page.current
  reverseStore.getData().page_size = reverseStore.page.pageSize

  return new Promise((resolve, jeject) => {
    reverseStore.page.loading = true
    get(reverseStore.getWhere()).then(res => {
      const list = res.data.map(item => {
        item.time = app.time.load(item.time)
        return item
      })
      reverseStore.setList(list)
      // 分页
      reverseStore.page.current = res.current_page
      reverseStore.page.pageSize = res.per_page
      reverseStore.page.total = res.total
      resolve(res)
    }).catch(res => {
      jeject(res)
    }).finally(() => {
      reverseStore.page.loading = false
    })
  })
}

// 重置请求
reverseStore.reset = async (page, size = null) => {
  reverseStore.page.current = page
  if(size) {
    reverseStore.page.pageSize = size
  }
  
  // 开始加载
  await reverseStore.get()
}

// 加载商品  传入订单数组
reverseStore.item = async (raw) => {
  const items = {}

  // 请求订单商品
  const orders = await item(raw.map(data => data.trade_order_id))
  // 循环订单
  orders.forEach(order => {
    // 使用对象key的不重复机制，来拿到所有商品的sku
    order.order_items.forEach(item => {
      items[item.order_item_id] = item
    })
  })

  return items
}

// 关联端口
reverseStore.goods = async (raw) => {
  const goods = {}

  // 请求sku对应的商品
  const goodsList = await limit({ number_in: raw.map(data => data.sku) })
  // 循环商品
  goodsList.forEach(item => {
    goods[item.number] = item
  })

  raw.forEach(data => {
    data.goods = goods[data.sku]
  })

  return raw
}


export default reverseStore